/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.hualu.zks.httpclient;

import com.hualu.lgproject.Model.File;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;

public class GetFileList {

    /**
     * @throws java.io.IOException
     */
    public StringBuilder res = null;
    private HttpResponse response;
    public static int loop_rest_num[] = new int[2]; // 存储循环次数和剩余次数,0:loopnum,1:restnum
    private DefaultHttpClient httpclient = new DefaultHttpClient();

    @SuppressWarnings("empty-statement")
    public ArrayList<File> getList(String URL, int Nodeid, int Index, int Count)
            throws IOException {

        String LoginURL = "http://" + URL + "/WAN/ttl_list.cgi";
        HttpPost httpost = new HttpPost(LoginURL);
        HttpParams params = httpclient.getParams();
        HttpConnectionParams.setConnectionTimeout(params, 5000);
        HttpConnectionParams.setSoTimeout(params, 5000);
        ArrayList<File> fileList1 = new ArrayList<>();
        int flag = 1;// 读取行数标志
        String STARTINDEX = String.valueOf(Index);
        String cCount = String.valueOf(Count);

        List<BasicNameValuePair> nvps = new ArrayList<>();// 设置协议信息
        nvps.add(new BasicNameValuePair("cCMD_ExEC.x", "100"));
        nvps.add(new BasicNameValuePair("cPARENTID", "/01/01/"));
        nvps.add(new BasicNameValuePair("cSORTTYPE", "0"));
        nvps.add(new BasicNameValuePair("SID", "12345678"));
        // 获取开始位置
        nvps.add(new BasicNameValuePair("cSTARTINDEX", STARTINDEX));
        nvps.add(new BasicNameValuePair("cCMD_EXEC.y", "100"));
        // 获取数目
        nvps.add(new BasicNameValuePair("cCOUNT", cCount));
        // nvps.add(new BasicNameValuePair("Host", "192.168.1.110"));
        nvps.add(new BasicNameValuePair("Host", URL));
		// nvps.add(new BasicNameValuePair("User-Agent",
        // "MEI-LAN-REMOTE-CALL"));
        nvps.add(new BasicNameValuePair("Expect", "100-continue"));

        try {
            // // 设置请求的数据
            httpost.setEntity(new UrlEncodedFormEntity(nvps, "SJIS"));
            httpost.setHeader("User-Agent", "MEI-LAN-REMOTE-CALL");
            response = httpclient.execute(httpost);
            // 获取响应信息
            HttpEntity entity = response.getEntity();
            InputStreamReader rr = new InputStreamReader(entity.getContent(),
                    "UTF-8");
            BufferedReader reader = new BufferedReader(rr);
            StringBuilder builder = new StringBuilder();

            String s_show[] = new String[9];
            // ///
            for (String line = reader.readLine(); line != null; line = reader
                    .readLine()) {

                File file = new File();
                file.setNodeId(Nodeid);
                flag++;
                if (flag > 4) {

                    builder.append(line);
                    String[] s = line.split(",");
                    int slength = s.length;
                    if (slength == 33) {
                        s_show[0] = s[1];
                        s_show[1] = s[7];// s_show[2] = s[8];
                        s_show[2] = s[8].substring(0, 2) + ":"
                                + s[8].substring(2, 4) + ":"
                                + s[8].substring(4, 6);
                        s_show[3] = s[9];
                        s_show[4] = s[12];
                        s_show[5] = s[31];
                        s_show[6] = s[32];
                        if (s_show[4].indexOf("\"") == 0) {
                            s_show[4] = s_show[4].substring(1,
                                    s_show[4].length()); // 去掉第一个 "
                        }
                        if (s_show[4].lastIndexOf("\"") == (s_show[4].length() - 1)) {
                            s_show[4] = s_show[4].substring(0,
                                    s_show[4].length() - 1); // 去掉最后一个 "
                        }
                    } else {
                        s_show[0] = s[1];
                        s_show[1] = s[7];
                        s_show[2] = s[8].substring(0, 2) + ":"
                                + s[8].substring(2, 4) + ":"
                                + s[8].substring(4, 6);
                        s_show[3] = s[9];
                        s_show[4] = s[12];
                        s_show[5] = s[31];
                        s_show[6] = s[32];
                        s_show[7] = s[33];
                        s_show[8] = s[34];
                        if (s_show[4].indexOf("\"") == 0) {
                            s_show[4] = s_show[4].substring(1,
                                    s_show[4].length()); // 去掉第一个 "
                        }
                        if (s_show[4].lastIndexOf("\"") == (s_show[4].length() - 1)) {
                            s_show[4] = s_show[4].substring(0,
                                    s_show[4].length() - 1); // 去掉最后一个 "
                        }
                    }
                    file.setFileId(URL+"_"+s_show[1]+"_"+s_show[2].replaceAll(":", ""));
                    file.setDate(s_show[1]);
                    file.setStartTime(s_show[2]);
                    file.setName(s_show[4]);
                    file.setLength(s_show[3]);
                    file.setTtsSize(s_show[5]);
                    file.setTtsUrl(s_show[6]);
                    file.setMp4Size(s_show[7]);
                    file.setMp4Url(s_show[8]);
                    fileList1.add(file);
                    s_show = new String[9];
                }
            }
            rr.close();
        } catch (IOException | IllegalStateException e) {
            //e.printStackTrace();
            System.err.println("httpclient的IO异常打印：" + e.getMessage());
            if (e.getMessage().contains("timed out")) {
                return null;
            }
        } finally {
            httpost.abort();
        }
        return fileList1;
    }

    /**
     * 获取全部列表
     *
     * @param URL
     * @param nodeId
     * @return
     * @throws IOException
     */
    public ArrayList<File> getAllList(String URL, int nodeId) throws IOException {
        ArrayList<File> allFileList = new ArrayList<>();
        int startindex;
        for (int i = 0; i < loop_rest_num[0]; i++) {
            startindex = i * 32;
            allFileList.addAll(getList(URL, nodeId, startindex, 32));
        }
        allFileList.addAll(getList(URL, nodeId, loop_rest_num[0] * 32,
                loop_rest_num[1]));
        return allFileList;
    }

    /**
     * 获取剩余列表
     *
     * @param URL
     * @param nodeId
     * @return
     * @throws IOException
     */
    public ArrayList<File> getRestList(String URL, int nodeId) throws IOException {
        ArrayList<File> restFileList = new ArrayList<>();
        ArrayList<File> restFileList1 = new ArrayList<>();
        int startindex;

        if (loop_rest_num[0] == 0) {
            return restFileList;
        }

        for (int i = 1; i < loop_rest_num[0]; i++) {
            startindex = i * 32;
            restFileList1 = getList(URL, nodeId, startindex, 32);
            if (restFileList1 == null) {
                return restFileList;
            } else {
                restFileList.addAll(restFileList1);
            }

        }
        restFileList.addAll(getList(URL, nodeId, loop_rest_num[0] * 32,
                loop_rest_num[1]));
        return restFileList;
    }

    /**
     * 获取最前面的列表，并且获取总文件个数
     *
     * @param URL
     * @param nodeId
     * @return
     * @throws IOException
     */
    public ArrayList<File> getFirstList(String URL, int nodeId) throws IOException {
        ArrayList<File> firstFileList = new ArrayList<>();
        String LoginURL = "http://" + URL + "/WAN/ttl_list.cgi";
        HttpPost httpost = new HttpPost(LoginURL);
        // int loopnum;//循环次数
        int flag = 1;// 读取行数标志

        HttpParams params = httpclient.getParams();
        HttpConnectionParams.setConnectionTimeout(params, 5000);
        HttpConnectionParams.setSoTimeout(params, 5000);
        List<BasicNameValuePair> nvps = new ArrayList<>();// 设置协议信息
        nvps.add(new BasicNameValuePair("cCMD_ExEC.x", "100"));
        nvps.add(new BasicNameValuePair("cPARENTID", "/01/01/"));
        nvps.add(new BasicNameValuePair("cSORTTYPE", "0"));
        nvps.add(new BasicNameValuePair("SID", "12345678"));
        // 获取开始位置
        nvps.add(new BasicNameValuePair("cSTARTINDEX", "0"));
        nvps.add(new BasicNameValuePair("cCMD_EXEC.y", "100"));
        // 获取数目
        nvps.add(new BasicNameValuePair("cCOUNT", "32"));
        nvps.add(new BasicNameValuePair("Host", URL));
        nvps.add(new BasicNameValuePair("Expect", "100-continue"));

        try {
            // 设置请求的数据
            httpost.setEntity(new UrlEncodedFormEntity(nvps, "SJIS"));
            httpost.setHeader("User-Agent", "MEI-LAN-REMOTE-CALL");
            response = httpclient.execute(httpost);
            // 获取响应信息
            HttpEntity entity = response.getEntity();
            InputStreamReader rr = new InputStreamReader(entity.getContent(),
                    "UTF-8");
            BufferedReader reader = new BufferedReader(rr);
            StringBuilder builder = new StringBuilder();
            String s_show[] = new String[9];

            // 显示需要的参数变量
            for (String line = reader.readLine(); line != null; line = reader
                    .readLine()) {
                File file;
                flag++;
                if (flag == 4) {
                    String[] ss = line.split(",");
                    System.out.println("文件总数目：" + ss[1]);
                    int allnum;
                    allnum = Integer.parseInt(ss[1]);
                    //loop_rest_num[0] = Math.round(allnum / 32);
                    loop_rest_num[0] = (int) Math.floor(allnum / 32);
                    loop_rest_num[1] = allnum % 32;
                    System.out.println("count" + allnum);
                }
                if (flag > 4) {
                    file = new File();
                    file.setNodeId(nodeId);
                    builder.append(line);
                    String[] s = line.split(",");
                    int slength = s.length;
                    if (slength == 33) {
                        s_show[0] = s[1];
                        s_show[1] = s[7];// s_show[2] = s[8];
                        s_show[2] = s[8].substring(0, 2) + ":"
                                + s[8].substring(2, 4) + ":"
                                + s[8].substring(4, 6);
                        s_show[3] = s[9];
                        s_show[4] = s[12];
                        s_show[5] = s[31];
                        s_show[6] = s[32];

                        if (s_show[4].indexOf("\"") == 0) {
                            s_show[4] = s_show[4].substring(1,
                                    s_show[4].length()); // 去掉第一个 "
                        }
                        if (s_show[4].lastIndexOf("\"") == (s_show[4].length() - 1)) {
                            s_show[4] = s_show[4].substring(0,
                                    s_show[4].length() - 1); // 去掉最后一个 "
                        }
                    } else {
                        s_show[0] = s[1];
                        s_show[1] = s[7];
                        s_show[2] = s[8].substring(0, 2) + ":"
                                + s[8].substring(2, 4) + ":"
                                + s[8].substring(4, 6);
                        s_show[3] = s[9];
                        s_show[4] = s[12];
                        s_show[5] = s[31];
                        s_show[6] = s[32];
                        s_show[7] = s[33];
                        s_show[8] = s[34];
                        if (s_show[4].indexOf("\"") == 0) {
                            s_show[4] = s_show[4].substring(1,
                                    s_show[4].length()); // 去掉第一个 "
                        }
                        if (s_show[4].lastIndexOf("\"") == (s_show[4].length() - 1)) {
                            s_show[4] = s_show[4].substring(0,
                                    s_show[4].length() - 1); // 去掉最后一个 "
                        }
                    }
                    file.setFileId(URL+"_"+s_show[1]+"_"+s_show[2].replaceAll(":", ""));
                    file.setDate(s_show[1]);
                    file.setStartTime(s_show[2]);
                    file.setName(s_show[4]);
                    file.setLength(s_show[3]);
                    file.setTtsSize(s_show[5]);
                    file.setTtsUrl(s_show[6]);
                    file.setMp4Size(s_show[7]);
                    file.setMp4Url(s_show[8]);
                    firstFileList.add(file);
                    s_show = new String[9];
                }

            }
        } catch (Exception e) {
//			e.printStackTrace();
            System.err.println("httpclient的IO异常打印：" + e.getMessage());
            if (e.getMessage().contains("timed out") || e.getMessage().contains("No route to host")) {
                return null;
            }
        } finally {
            httpost.abort();
        }

        return firstFileList;
    }

    public Integer getFileCount(String URL, int nodeId) throws IOException {
        System.err.println("ip:"+URL+"\nid:"+nodeId);
        String LoginURL = "http://" + URL + "/WAN/ttl_list.cgi";
        HttpPost httpost = new HttpPost(LoginURL);
        // int loopnum;//循环次数
        int flag = 1;// 读取行数标志

        HttpParams params = httpclient.getParams();
        HttpConnectionParams.setConnectionTimeout(params, 6000);
        HttpConnectionParams.setSoTimeout(params,6000);
        List<BasicNameValuePair> nvps = new ArrayList<>();// 设置协议信息
        nvps.add(new BasicNameValuePair("cCMD_ExEC.x", "100"));
        nvps.add(new BasicNameValuePair("cPARENTID", "/01/01/"));
        nvps.add(new BasicNameValuePair("cSORTTYPE", "0"));
        nvps.add(new BasicNameValuePair("SID", "12345678"));
        // 获取开始位置
        nvps.add(new BasicNameValuePair("cSTARTINDEX", "0"));
        nvps.add(new BasicNameValuePair("cCMD_EXEC.y", "100"));
        // 获取数目
        nvps.add(new BasicNameValuePair("cCOUNT", "1"));
        nvps.add(new BasicNameValuePair("Host", URL));
        nvps.add(new BasicNameValuePair("Expect", "100-continue"));

        try {
            // 设置请求的数据
            httpost.setEntity(new UrlEncodedFormEntity(nvps, "SJIS"));
            httpost.setHeader("User-Agent", "MEI-LAN-REMOTE-CALL");
            response = httpclient.execute(httpost);
            // 获取响应信息
            HttpEntity entity = response.getEntity();
            InputStreamReader rr = new InputStreamReader(entity.getContent(),
                    "UTF-8");
            BufferedReader reader = new BufferedReader(rr);
            StringBuilder builder = new StringBuilder();
System.err.println("1111111111");
            // 显示需要的参数变量
            for (String line = reader.readLine(); line != null; line = reader
                    .readLine()) {
                flag++;
                if (flag == 4) {
                    String[] ss = line.split(",");
                    System.out.println("文件总数目：" + ss[1]);
                    int allnum;
                    allnum = Integer.parseInt(ss[1]);
                    //loop_rest_num[0] = Math.round(allnum / 32);
                    loop_rest_num[0] = (int) Math.floor(allnum / 32);
                    loop_rest_num[1] = allnum % 32;
                    System.out.println("count" + loop_rest_num[1]);
                    return allnum;
                }
            }
        } catch (Exception e) {
//			e.printStackTrace();
            System.err.println("httpclient的IO异常打印：" + e.getMessage());
            if (e.getMessage().contains("timed out") || e.getMessage().contains("No route to host")) {
                return null;
            }
        } finally {
            httpost.abort();
        }
        return null;
    }
    
    public File getLastFile(String URL, Integer nodeId, Integer count) throws IOException {
        String LoginURL = "http://" + URL + "/WAN/ttl_list.cgi";
        HttpPost httpost = new HttpPost(LoginURL);
        // int loopnum;//循环次数
        int flag = 1;// 读取行数标志

        HttpParams params = httpclient.getParams();
        HttpConnectionParams.setConnectionTimeout(params, 5000);
        HttpConnectionParams.setSoTimeout(params, 5000);
        List<BasicNameValuePair> nvps = new ArrayList<>();// 设置协议信息
        nvps.add(new BasicNameValuePair("cCMD_ExEC.x", "100"));
        nvps.add(new BasicNameValuePair("cPARENTID", "/01/01/"));
        nvps.add(new BasicNameValuePair("cSORTTYPE", "0"));
        nvps.add(new BasicNameValuePair("SID", "12345678"));
        // 获取开始位置
        nvps.add(new BasicNameValuePair("cSTARTINDEX", String.valueOf(count-1)));
        nvps.add(new BasicNameValuePair("cCMD_EXEC.y", "100"));
        // 获取数目
        nvps.add(new BasicNameValuePair("cCOUNT", "1"));
        nvps.add(new BasicNameValuePair("Host", URL));
        nvps.add(new BasicNameValuePair("Expect", "100-continue"));

        try {
            // 设置请求的数据
            httpost.setEntity(new UrlEncodedFormEntity(nvps, "SJIS"));
            httpost.setHeader("User-Agent", "MEI-LAN-REMOTE-CALL");
            response = httpclient.execute(httpost);
            // 获取响应信息
            HttpEntity entity = response.getEntity();
            InputStreamReader rr = new InputStreamReader(entity.getContent(),
                    "UTF-8");
            BufferedReader reader = new BufferedReader(rr);
            StringBuilder builder = new StringBuilder();
            String s_show[] = new String[9];

            // 显示需要的参数变量
            for (String line = reader.readLine(); line != null; line = reader
                    .readLine()) {
                File file;
                flag++;
                if (flag == 4) {
                    String[] ss = line.split(",");
                    System.out.println("文件总数目：" + ss[1]);
                    int allnum;
                    allnum = Integer.parseInt(ss[1]);
                    //loop_rest_num[0] = Math.round(allnum / 32);
                    loop_rest_num[0] = (int) Math.floor(allnum / 32);
                    loop_rest_num[1] = allnum % 32;
                    System.out.println("count" + allnum);
                }
                if (flag > 4) {
                    file = new File();
                    file.setNodeId(nodeId);
                    builder.append(line);
                    String[] s = line.split(",");
                    int slength = s.length;
                    if (slength == 33) {
                        s_show[0] = s[1];
                        s_show[1] = s[7];// s_show[2] = s[8];
                        s_show[2] = s[8].substring(0, 2) + ":"
                                + s[8].substring(2, 4) + ":"
                                + s[8].substring(4, 6);
                        s_show[3] = s[9];
                        s_show[4] = s[12];
                        s_show[5] = s[31];
                        s_show[6] = s[32];

                        if (s_show[4].indexOf("\"") == 0) {
                            s_show[4] = s_show[4].substring(1,
                                    s_show[4].length()); // 去掉第一个 "
                        }
                        if (s_show[4].lastIndexOf("\"") == (s_show[4].length() - 1)) {
                            s_show[4] = s_show[4].substring(0,
                                    s_show[4].length() - 1); // 去掉最后一个 "
                        }
                    } else {
                        s_show[0] = s[1];
                        s_show[1] = s[7];
                        s_show[2] = s[8].substring(0, 2) + ":"
                                + s[8].substring(2, 4) + ":"
                                + s[8].substring(4, 6);
                        s_show[3] = s[9];
                        s_show[4] = s[12];
                        s_show[5] = s[31];
                        s_show[6] = s[32];
                        s_show[7] = s[33];
                        s_show[8] = s[34];
                        if (s_show[4].indexOf("\"") == 0) {
                            s_show[4] = s_show[4].substring(1,
                                    s_show[4].length()); // 去掉第一个 "
                        }
                        if (s_show[4].lastIndexOf("\"") == (s_show[4].length() - 1)) {
                            s_show[4] = s_show[4].substring(0,
                                    s_show[4].length() - 1); // 去掉最后一个 "
                        }
                    }
                    file.setFileId(URL+"_"+s_show[1]+"_"+s_show[2].replaceAll(":", ""));
                    file.setDate(s_show[1]);
                    file.setStartTime(s_show[2]);
                    file.setName(s_show[4]);
                    file.setLength(s_show[3]);
                    file.setTtsSize(s_show[5]);
                    file.setTtsUrl(s_show[6]);
                    file.setMp4Size(s_show[7]);
                    file.setMp4Url(s_show[8]);
//                    firstFileList.add(file);
                    return file;
//                    s_show = new String[9];
                }

            }
        } catch (Exception e) {
//			e.printStackTrace();
            System.err.println("httpclient的IO异常打印：" + e.getMessage());
            if (e.getMessage().contains("timed out") || e.getMessage().contains("No route to host")) {
                return null;
            }
        } finally {
            httpost.abort();
        }

        return null;
    }

    public int checkSleep(String URL) throws IOException {
        String LoginURL = "http://" + URL + "/WAN/ttl_list.cgi";
        HttpPost httpost = new HttpPost(LoginURL);

        HttpParams params = httpclient.getParams();
        HttpConnectionParams.setConnectionTimeout(params, 5000);
        HttpConnectionParams.setSoTimeout(params, 5000);
        List<BasicNameValuePair> nvps = new ArrayList<>();// 设置协议信息
        nvps.add(new BasicNameValuePair("cCMD_ExEC.x", "100"));
        nvps.add(new BasicNameValuePair("cPARENTID", "/01/01/"));
        nvps.add(new BasicNameValuePair("cSORTTYPE", "0"));
        nvps.add(new BasicNameValuePair("SID", "12345678"));
        // 获取开始位置
        nvps.add(new BasicNameValuePair("cSTARTINDEX", "0"));
        nvps.add(new BasicNameValuePair("cCMD_EXEC.y", "100"));
        // 获取数目
        nvps.add(new BasicNameValuePair("cCOUNT", "1"));
        nvps.add(new BasicNameValuePair("Host", URL));
        nvps.add(new BasicNameValuePair("Expect", "100-continue"));

        try {
            // 设置请求的数据
            httpost.setEntity(new UrlEncodedFormEntity(nvps, "SJIS"));
            httpost.setHeader("User-Agent", "MEI-LAN-REMOTE-CALL");
            response = httpclient.execute(httpost);
            // 获取响应信息
            HttpEntity entity = response.getEntity();
            InputStreamReader rr = new InputStreamReader(entity.getContent(),
                    "UTF-8");
            BufferedReader reader = new BufferedReader(rr);
            StringBuilder builder = new StringBuilder();
            String s_show[] = new String[9];
            // 显示需要的参数变量
            for (String line = reader.readLine(); line != null; line = reader
                    .readLine()) {
//                                        System.out.println("回复的字符：" + line);
                String[] ss = line.split(",");
//					System.out.println("第一组字符：" + ss[0]);
                if ("16".equals(ss[0])) {
                    return 1;
                } else {
                    return 0;
                }
            }
        } catch (Exception e) {
//			e.printStackTrace();
            System.err.println("httpclient的IO异常打印：" + e.getMessage());
            if (e.getMessage().contains("timed out") || e.getMessage().contains("No route to host")) {
                return -1;
            }
        } finally {
            httpost.abort();
        }
        return -1;
    }
}
